<?php
class AuctionService
{
	/**
	 * 查询列表
	 */
	public function getListBySql($sql)
	{
		$list = array();
		$query = DB::query($sql);
		while($data = DB::fetch($query))
		{
			if(!parseUrl($data['img']))
				$data['img'] = SITE_PATH.$data['img'];

			$data['end_time_format']  = toDate($data['end_time']);
			$data['end_time_js']  = toDate($data['end_time'],'r');
			$data['base_price_format'] = "¥".floatval($data['base_price']);
			$data['buyout_price_format'] = "¥".floatval($data['buyout_price']);
			$data['url'] = U("auction/show",array("id"=>$data['id']));
			$list[] = $data;
		}

		return $list;
	}

	/**
	 * 热门竞拍
	*/
	public function getHotList()
	{
		$sql = 'SELECT id,name,img,base_price,end_time,buyout_price
				FROM '.DB::table('auction').'
				WHERE is_hot = 1 AND (begin_time <= '.TIME_UTC.' OR begin_time = 0)
				AND (end_time > '.TIME_UTC.' OR end_time = 0) AND auction_status = 0
				ORDER BY sort ASC,end_time ASC,id DESC';

		return $this->getListBySql($sql);
	}

	/**
	 * 竞拍专区
	*/
	public function getList()
	{
		$sql = 'SELECT id,name,img,base_price,end_time,buyout_price
				FROM '.DB::table('auction').'
				WHERE is_hot = 0 AND (begin_time <= '.TIME_UTC.' OR begin_time = 0)
				AND (end_time > '.TIME_UTC.' OR end_time = 0) AND auction_status = 0
				ORDER BY sort ASC,end_time ASC,id DESC';

		return $this->getListBySql($sql);
	}

	public function getItem($id)
	{
		$cache_path = FANWE_ROOT.'./public/auction/auction/'.$id.'.fanwe';
		if(!@include $cache_path)
		{
			$auction = DB::fetchFirst('SELECT * FROM '.DB::table('auction').' AS a
				WHERE id = '.$id.' AND (begin_time <= '.TIME_UTC.' OR begin_time = 0)');

			if($auction)
			{
				$auction['citys'] = array();
				$query = DB::query('SELECT ac.city_id,gc.name FROM '.DB::table('auction_city').' AS ac
									LEFT JOIN '.DB::table('group_city').' AS gc ON gc.id = ac.city_id
									WHERE ac.auction_id = '.$id.' ORDER BY gc.sort ASC');

				while($data = DB::fetch($query))
				{
					$auction['citys'][] = $data;
				}

				if(!parseUrl($auction['img']))
					$auction['img'] = SITE_PATH.$auction['img'];

				$auction['end_time_format']  = toDate($auction['end_time']);
				$auction['end_time_js']  = toDate($auction['end_time'],'r');
				$auction['base_price_format'] = "¥".floatval($auction['base_price']);
				$auction['amplitude_format'] = "¥".floatval($auction['amplitude']);
				$auction['buyout_price_format'] = "¥".floatval($auction['buyout_price']);
				$auction['pre_pay_format'] = "¥".floatval($auction['pre_pay']);
				$auction['auction_type_name'] = $auction['auction_type'] == 0 ? "广 告 位" : "团购排序";
				$auction['billing_type_name'] = $auction['billing_type'] == 0 ? "点击付费" : "固定费用";
				$auction['validity_begin_time_format'] = toDate($auction['validity_begin_time']);
				$auction['validity_end_time_format'] = toDate($auction['validity_end_time']);
				$this->setAuction($auction);
			}
		}

		return $auction;
	}

	public function setAuction($auction)
	{
		$cache_path = FANWE_ROOT.'./public/auction/auction/'.$auction['id'].'.fanwe';
		$content = "<?php\r\n".'$auction = '.var_export($auction,true).";\r\n?>";
		writeFile($cache_path,$content);
	}

	public function auctionComplete($auction)
	{
		if($auction['user_id'] > 0)
		{
			$statistic['auction_id'] = $auction['id'];
			$statistic['num'] = 0;
			$statistic['statistic_time'] = 0;
			$statistic['freeze_money'] = AuctionService::getFreezeMoney($auction['id'],$auction['user_id'],false);
			AuctionService::deleteFreezeMoney($auction['id'],$auction['user_id']);
			
			if($auction['billing_type'] == 0)
				$statistic['outlay_money'] = 0;
			else
				$statistic['outlay_money'] = $statistic['freeze_money'];
			
			DB::insert('auction_statistic',$statistic,false,true);
			
			$cron['type'] = 'auction';
			$cron['run_time'] = $auction['validity_begin_time'];
			$cron['func'] = 'begin';
			$cron['data'] = $auction['id'];
			DB::insert('cron',$cron);

			if($auction['validity_end_time'] > 0)
			{
				$cron['type'] = 'auction';
				$cron['run_time'] = $auction['validity_end_time'];
				$cron['func'] = 'end';
				$cron['data'] = $auction['id'];
				DB::insert('cron',$cron);
			}
		}
	}

	public function runCron($cron_list)
	{
		foreach($cron_list as $cron)
		{
			$fun = $cron['func'].'Cron';
			$this->$fun(intval($cron['data']));
		}
	}

	public function beginCron($id)
	{
		global $_FANWE;
		
		$auction = AuctionService::getItem($id);
		if($auction)
		{
			$result['auction_id'] = $id;
			$result['auction_type'] = $auction['auction_type'];
			$result['rec_id'] = intval($auction['rec_id']);
			$result['rec_data'] = $auction['rec_data'];

			if($auction['auction_type'] == 1)
			{
				$result['rec_data'] = 10000 - intval($auction['rec_data']);
				$site = S('Site')->getSiteByUserID($auction['user_id']);
				if($site)
					$result['rec_id'] = intval($site['id']);
			}

			if($result['rec_id'] > 0 && DB::insert('auction_result',$result))
			{
				if($auction['auction_type'] == 1)
				{
					if(count($auction['citys']) > 0 && $auction['citys'][0]['city_id'] > 0)
					{
						foreach($auction['citys'] as $city)
						{
							$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);
							$data = array(
								'auction_id'=>$id,
								'site_id'=>$result['rec_id'],
								'city_id'=>$city['city_id'],
								'goods_id'=>$goods_id,
								'auction_sort'=>$result['rec_data']
							);
							
							DB::insert('auction_city_goods',$data,false,true);
						}
					}
					else
					{
						require_once import("function/cache");
						loadCache('city');

						foreach($_FANWE['cache']['city']['all'] as $city)
						{
							$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);
							$data = array(
								'auction_id'=>$id,
								'site_id'=>$result['rec_id'],
								'city_id'=>$city['id'],
								'goods_id'=>$goods_id,
								'auction_sort'=>$result['rec_data']
							);
							
							DB::insert('auction_city_goods',$data,false,true);
						}
					}

					clearDir(FANWE_ROOT.'./public/tpl/caches/page_index_index');
				}
				
				AuctionService::createAuctionClickTable($id);
			}
		}
	}

	public function endCron($id)
	{
		$result = DB::query('SELECT * FROM '.DB::table('auction_result')." WHERE auction_id = '$id'");
		if($result)
		{
			DB::delete('auction_result','auction_id = '.$id);
			$auction = AuctionService::getItem($id);
			if($auction)
			{
				if($auction['auction_type'] == 1)
				{
					AuctionService::stopAuction($id,'goods');
				}
				else
				{
					AuctionService::stopAuction($id,'adv');
				}
				
				$statistic = DB::fetchFirst('SELECT * FROM '.DB::table('auction_statistic').' WHERE auction_id = '.$id);
				if($auction['billing_type'] == 0)
				{
					$money = $statistic['freeze_money'] - $statistic['outlay_money'];
					if($money > 0)
					{
						$ratio = S('bbs')->getECRatio();
						$money = $money * $ratio;
						S('User')->updateUserScore($auction['user_id'],'Auction','End','推广 '.$auction['name'].' 结束,退回冻结剩余积分',$id,$money);
						DB::query('UPDATE '.DB::table('auction_statistic').' SET freeze_money = outlay_money WHERE auction_id = '.$id);
					}
				}
			}
		}
	}

	private function createAuctionClickTable($id)
	{
		$sql = "CREATE TABLE IF NOT EXISTS `".DB::table('auction_click_'.$id)."` (
                `ip` varchar(30) NOT NULL DEFAULT '',
				`referer` varchar(255) NOT NULL DEFAULT '',
				`rec_id` mediumint(8) NOT NULL DEFAULT '0',
				`rec_name` varchar(255) NOT NULL DEFAULT '',
				`click_time` int(11) NOT NULL DEFAULT '0',
				KEY `ip` (`ip`),
				KEY `rec_id` (`rec_id`)) ENGINE = MYISAM";
        
    	DB::query($sql);
    	DB::query('TRUNCATE TABLE '.DB::table('auction_click_'.$id));
	}
	
	public function insertAuctionClick($id,$args,$type)
	{
		global $_FANWE;
		
		$marketing = getCookie('marketing');;
		if(empty($marketing) || authcode($marketing) != $_FANWE['marketing'])
			return;
		
		$ip = $_FANWE['client_ip'];
		$referer = $_SERVER['HTTP_REFERER'];
		
		if(empty($referer) || strpos($referer,$_FANWE['host']) === false)
			return;
		
		$is_normal = true;
		
		$ip_cache = FANWE_ROOT.'./public/auction/ip/'.$ip.'.fanwe';
		
		if(!@include $ip_cache)
		{
			$ip_data['time'] = TIME_UTC;
			$ip_data['denied'] = 0;
			$ip_data['cooling'] = 0;
			$ip_data['click_count'] = 0;
		}
		else
		{
			$today_time = getTodayTime();
			if($today_time > $ip_data['time'])
			{
				$ip_data['cooling'] = 0;
				$ip_data['denied'] = 0;
				$ip_data['click_count'] = 0;
			}
			else
			{
				if($ip_data['cooling'] > 0 && $ip_data['cooling'] < TIME_UTC)
				{
					$ip_data['cooling'] = 0;
					$ip_data['denied'] = 0;
				}
				
				if($ip_data['cooling'] >= TIME_UTC)
					$is_normal = false;
				else
				{
					if(TIME_UTC - $ip_data['time'] < $_FANWE['setting']['auction_click_time'])
					{
						$is_normal = false;
						$ip_data['denied']++;
					}
					else
						$ip_data['denied'] = 0;
					
					if($ip_data['denied'] >= $_FANWE['setting']['auction_click_denied'])
						$ip_data['cooling'] = TIME_UTC + intval(floatval($_FANWE['setting']['auction_click_blocked']) * 3600);
				}
			}
		}
		
		if($ip_data['click_count'] > $_FANWE['setting']['auction_day_max_click'])
			return;
		else
		{
			$ip_data['time'] = TIME_UTC;
			$ip_data['click_count']++;
		}
		
		$content = "<?php\r\n".'$ip_data = '.var_export($ip_data,true).";\r\n?>";
		writeFile($ip_cache,$content);
		
		if(!$is_normal)
			return;
		
		if($type == 'goods')
		{
			$goods_name = DB::resultFirst('SELECT name FROM '.DB::table('goods_now').' WHERE id = '.$id);
			if(!empty($goods_name))
			{
				$city_id = intval($_FANWE['current_city']['id']);
				$res = DB::query('SELECT * FROM '.DB::table('auction_city_goods').' WHERE goods_id = '.$id.' AND city_id = '.$city_id.' ORDER BY auction_sort DESC');
				$acgs = array();
				while($data = DB::fetch($res))
				{
					$acgs[$data['auction_sort']][] = $data['auction_id'];
				}
				
				$auction_id = 0;
				$acgs = current($acgs);

				if(count($acgs) == 1)
				{
					$auction = AuctionService::getItem(intval($acgs[0]));
					if($auction)
						$auction_id = $acgs[0];
				}
				elseif(count($acgs) > 1)
				{
					$city_counts = array();
					$all_ids = array();
					
					foreach($acgs as $aid)
					{
						$auction = AuctionService::getItem($aid);
						if($auction)
						{
							if($auction['citys'][0]['city_id'] == 0)
								$all_ids[] = $aid;
							else
								$city_counts[count($auction['citys'])][] = $aid;
						}
					}
					
					if(count($city_counts) > 0)
					{
						krsort($city_counts);
						$aids = current($city_counts);
						$auction_id = $aids[array_rand($aids)];
					}
					else
						$auction_id = $all_ids[array_rand($all_ids)];
				}
				
				if($auction_id > 0)
				{
					$auction = AuctionService::getItem($auction_id);
					$statistic = DB::fetchFirst('SELECT * FROM '.DB::table('auction_statistic').' WHERE auction_id = '.$auction_id);
					if($auction['billing_type'] == 0)
					{
						$bid_price = AuctionService::getAuctionPrice($auction_id);
						$statistic['outlay_money'] += $bid_price;
						if($statistic['outlay_money'] >= $statistic['freeze_money'])
							AuctionService::stopAuction($auction_id,'goods');
					}
					
					$statistic['num']++;
					$statistic['statistic_time'] = TIME_UTC;
					DB::update('auction_statistic',$statistic,'auction_id = '.$auction_id);
					
					$click_log['ip'] = $ip;
					$click_log['referer'] = $referer;
					$click_log['rec_id'] = $id;
					$click_log['rec_name'] = $goods_name;
					$click_log['click_time'] = TIME_UTC;
					DB::insert('auction_click_'.$auction_id,$click_log);
				}
			}
		}
		elseif($type == 'adv')
		{
			$auction = AuctionService::getItem($args['auction_id']);
			if($auction)
			{
				$auction_id = $auction['id'];
				$statistic = DB::fetchFirst('SELECT * FROM '.DB::table('auction_statistic').' WHERE auction_id = '.$auction_id);
				if($auction['billing_type'] == 0)
				{
					$bid_price = AuctionService::getAuctionPrice($auction_id);
					$statistic['outlay_money'] += $bid_price;
					if($statistic['outlay_money'] >= $statistic['freeze_money'])
						AuctionService::stopAuction($auction_id,'adv');
				}
				
				$statistic['num']++;
				$statistic['statistic_time'] = TIME_UTC;
				DB::update('auction_statistic',$statistic,'auction_id = '.$auction_id);
				
				$click_log['ip'] = $ip;
				$click_log['referer'] = $referer;
				$click_log['rec_id'] = $id;
				$click_log['rec_name'] = $args['name'];
				$click_log['click_time'] = TIME_UTC;
				DB::insert('auction_click_'.$auction_id,$click_log);
			}
		}
	}
	
	private function stopAuction($id,$type)
	{
		if($type == 'goods')
			DB::query('UPDATE '.DB::table('auction_city_goods').' SET status = 0 WHERE auction_id = '.$id);
		elseif($type == 'adv')
			DB::query('UPDATE '.DB::table('adv').' SET status = 0 WHERE auction_id = '.$id);
	}

	public function insertAuctionLog($log)
	{
		return DB::insert('auction_log',$log);
	}

	//获取竞拍当前的最高价格
	public function getAuctionPrice($id)
	{
		return floatval(DB::resultFirst('SELECT bid_price FROM '.DB::table('auction_bid')." WHERE auction_id = '$id'"));
	}

	public function getAuctionBid($id)
	{
		$cache_path = FANWE_ROOT.'./public/auction/bid/'.$id.'.fanwe';
		if(!@include $cache_path)
			$bid = false;

		return $bid;
	}

	public function setAuctionBid($id,$info)
	{
		$cache_path = FANWE_ROOT.'./public/auction/bid/'.$id.'.fanwe';
		$bid = array();
		$bid['auction_id'] = $id;
		$bid['bid_price'] = $info['price'];
		DB::insert('auction_bid',$bid,false,true);
		$content = "<?php\r\n".'$bid = '.var_export($info,true).";\r\n?>";
		writeFile($cache_path,$content);
	}

	public function getAuctionRecords($id)
	{
		$cache_path = FANWE_ROOT.'./public/auction/record/'.$id.'.fanwe';
		if(!@include $cache_path)
			$records = false;

		return $records;
	}

	public function setAuctionRecords($id,$info)
	{
		$cache_path = FANWE_ROOT.'./public/auction/record/'.$id.'.fanwe';
		if(!@include $cache_path)
			$records = array();

		if(count($records) >= 20)
			array_pop($records);

		array_unshift($records,$info);
		$content = "<?php\r\n".'$records = '.var_export($records,true).";\r\n?>";
		writeFile($cache_path,$content);
	}

	public function getAuctionRanks($id)
	{
		$cache_path = FANWE_ROOT.'./public/auction/rank/'.$id.'.fanwe';
		if(!@include $cache_path)
			$ranks = false;

		return $ranks;
	}

	public function setAuctionRanks($id,$info)
	{
		$cache_path = FANWE_ROOT.'./public/auction/rank/'.$id.'.fanwe';
		if(!@include $cache_path)
			$ranks = array();

		if(isset($ranks[$info['username']]))
			unset($ranks[$info['username']]);
		else
		{
			if(count($ranks) >= 20)
				array_pop($ranks);
		}

		$ranks = array_merge(array($info['username']=>$info),$ranks);
		$content = "<?php\r\n".'$ranks = '.var_export($ranks,true).";\r\n?>";
		writeFile($cache_path,$content);
	}

	//获取会员在此竞拍已冻结的金额
	public function getFreezeMoney($id,$uid,$is_cache = false)
	{
		$freeze_money = 0;

		if($is_cache)
			@include FANWE_ROOT.'./public/auction/user/'.$id.'_'.$uid.'.fanwe';
		else
			$freeze_money = floatval(DB::resultFirst('SELECT money FROM '.DB::table('freeze_money')." WHERE auction_id = '$id' AND uid = '$uid'"));

		return $freeze_money;
	}
	
	//获取会员在此竞拍已冻结的金额
	public function deleteFreezeMoney($id,$uid)
	{
		DB::query('DELETE FROM '.DB::table('freeze_money')." WHERE auction_id = '$id' AND uid = '$uid'");
	}

	//设置会员在此竞拍已冻结的金额，并返回其他会员在此竞拍已冻结的金额
	public function setFreezeMoney($id,$uid,$money,$freeze_money)
	{
		$ratio = S('Bbs')->getECRatio();
		
		$freeze = array();
		$freeze['uid'] = $uid;
		$freeze['auction_id'] = $id;
		$freeze['money'] = $money;
		DB::insert('freeze_money',$freeze,false,true);
		
		$auction = AuctionService::getItem($id);

		if(DB::affectedRows() == 1)
		{
			S('User')->updateUserScore($uid,'Auction','Freeze','参加竞拍 '.$auction['name'].' 冻结积分',$id,-($money * $ratio),true);
		}
		
		if($money - $freeze_money == 0)
		{
			S('User')->updateUserScore($uid,'Auction','Freeze','参加竞拍 '.$auction['name'].' 冻结积分',$id,-(($money - $freeze_money) * $ratio),true);
		}
		
		$cache_path = FANWE_ROOT.'./public/auction/user/'.$id.'_'.$uid.'.fanwe';
		$content = "<?php\r\n".'$freeze_money = '.var_export($money,true).";\r\n?>";
		writeFile($cache_path,$content);

		$query = DB::query('SELECT uid,money FROM '.DB::table('freeze_money')." WHERE auction_id = '$id' AND uid <> '$uid'");
		while($data = DB::fetch($query))
		{
			$cache_path = FANWE_ROOT.'./public/auction/user/'.$id.'_'.$data['uid'].'.fanwe';
			@unlink($cache_path);
			DB::delete('freeze_money',"auction_id = '$id' AND uid = '$data[uid]'");
			S('User')->updateUserScore($uid,'Auction','Freeze','退回竞拍 '.$auction['name'].' 冻结积分',$id,-(($money - $freeze_money) * $ratio),true);
		}
	}
}
?>